package com.example.controller;

import ch.qos.logback.core.pattern.util.RegularEscapeUtil;
import com.example.comm.Result;
import com.example.controller.request.CategoryRequest;
import com.example.controller.request.PeriodicalRequest;
import com.example.dao.PeriodicalDao;
import com.example.dao.PeriodicalSpecification;
import com.example.entity.Periodical;
import com.example.service.UserService;
import jakarta.persistence.criteria.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/periodical")
public class PeriodicalController {
    @Autowired
    private PeriodicalDao periodicalDao;

    // 新增
    @PostMapping("/save")
    public Result save(@RequestBody Periodical periodical) {
        periodicalDao.save(periodical);
        return Result.success();
    }

    // 修改
    @PostMapping("/update")
    public Result update(@RequestBody Periodical periodical) {
        periodicalDao.save(periodical);
        return Result.success();
    }

    // 删除
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        periodicalDao.deleteById(id);
        return Result.success();
    }


    @PostMapping("/page")
    public Result page(@RequestBody  PeriodicalRequest periodicalRequest) {
        Pageable pageable = PageRequest.of(periodicalRequest.getPageNum() - 1, periodicalRequest.getPageSize(), Sort.by(Sort.Direction.DESC, "id"));
        System.out.println(periodicalRequest.getCategories());
        Specification<Periodical> specification = new PeriodicalSpecification(periodicalRequest);
        Page<Periodical> page = periodicalDao.findAll(specification, pageable);
        return Result.success(page);
    }

    @GetMapping("/findAll")
    public Result findAll() {
        return Result.success(periodicalDao.findAll());
    }

    @PostMapping("/getCate")
    public Result page(@RequestBody CategoryRequest categoryRequest){
        String category = categoryRequest.getCategory();
        List list=periodicalDao.findAllByCategories(category);
        return  Result.success(list);
    }

}
